import os
from fabric.api import *
from fabric.contrib import files, console
import commands

## UTILITIES
#
# Insired by cuisine
# License   : Revised BSD License
# 

def _file_ensure_append( location, text ):
    '''
    appends text to the target file location.
    '''
#    if not os.path.isfile(location):
# you need to use the following in this case because the target file
# will not not always be on the local system, otherwise, great python
    if not files.exists(location):
        print('not found!')
        run('touch %(location)s')
    print('### ensure append')
    contents = _file_read(location)
    if text in contents:
        print('text found in contents, no append require')
    else:
        print('appending file')
        return run("echo '%s' >> %s" % (text, location))


def _locate_program(executable):
    '''
    Get the location of an executable
    '''
    return run('which %s' % executable)

def _file_read( location ):
    '''
    Reads the *remote* file at the given location.
    '''
    return run("cat '%s'" % (location))

def _file_ensure( location ):
    '''
    If the specified location does not exits
    create it, otherwise do nothing
    '''
#    if not os.path.isfile(location):
    if not files.exists(location):
        run('touch %s' % (location))
def _file_append( location, text ):
    '''
    appends text to the target file location.
    '''
    return run("echo '%s' >> %s" % (text, location))

def _file_ensure_append( location, text ):
    '''
    appends text to the target file location.
    '''
#    if not os.path.isfile(location):
    if not files.exists(location):
        print('not found!')
        run('touch %(location)s')
    print('### ensure append')
    contents = _file_read(location)
    if text in contents:
        print('text found in contents, no append require')
    else:
        print('appending file')
        return run("echo '%s' >> %s" % (text, location))

def python_ver():
    '''
    # get the python version on target
    requires import commands
    '''
   # add try statement?
    pvstat, output = commands.getstatusoutput('python -V')
    if pvstat == 0:
        PythonVersion = output
        run('echo %s' % PythonVersion)
    # if python version check generates a return code other than O
    else:
        print 'python version check error:', pvstat

def get_platform():
    '''
    Get current os type
    '''
    env.platform = sys.platform
    if 'linux' in env.platform:
        print('You are running linux version %s' % env.platform)